package edu.hawaii.myisern.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;

/**
 * Provides a web interface for login.
 * 
 * This class is modified from the bugzooky example.
 * 
 * @author Edward Kim
 * @author JianFei Liao
 * @author KaYee Leung
 */
public class LoginActionBean implements ActionBean {

  /** The username. */
  @Validate(required = true) private String username;

  /** The password. */
  @Validate(required = true) private String password;

  /** Required by the ActionBean interface. */
  private ActionBeanContext context;

  /**
   * Returns the context. Required by the interface.
   * 
   * @return the ActionBeanContext.
   */
  public ActionBeanContext getContext() {
    return context;
  }

  /**
   * Sets the context. Required by the interface.
   * 
   * @param context The ActionBeanContext to set.
   */
  public void setContext(ActionBeanContext context) {
    this.context = context;
  }

  /**
   * Sets the user name.
   * 
   * @param name The new user name to be set.
   */
  public void setUsername(String name) {
    this.username = name;
  }

  /**
   * Sets the password.
   * 
   * @param password The new password to set.
   */
  public void setPassword(String password) {
    this.password = password;
  }

  /**
   * Verifies the login process.
   * 
   * @return A new resolution for the index page.
   */
  @DefaultHandler
  public Resolution login() {
    ValidationErrors errors = new ValidationErrors();
    // check if the username and password are correct.
    if (!"isern".equals(this.username)) {
      errors.add("wrongUsername", new SimpleError("Username is incorrect."));
      this.getContext().setValidationErrors(errors);
      return this.getContext().getSourcePageResolution();
    }
    
    if (!"password".equals(this.password)) {
      errors.add("this.username", new SimpleError("Password is incorrect."));
      this.getContext().setValidationErrors(errors);
      return this.getContext().getSourcePageResolution();
    }
    
    // allows the other url by setting a session
    getContext().getRequest().getSession().setAttribute("user", username);
    return new RedirectResolution("/index.jsp");
  } 
}